/**
 * jims
 */
package com.jims.master.modules.doctor.service;

import com.google.common.collect.Lists;
import com.jims.master.common.data.StringData;
import com.jims.master.common.persistence.Page;
import com.jims.master.common.service.CrudService;
import com.jims.master.common.utils.*;
import com.jims.master.common.web.impl.BaseDto;
import com.jims.master.modules.doctor.dao.ClinicMasterDao;
import com.jims.master.modules.doctor.dao.PatMasterIndexDao;
import com.jims.master.modules.doctor.dao.PatVisitDao;
import com.jims.master.modules.doctor.entity.*;
import com.jims.master.modules.finance.dao.InpBillDetailDao;
import com.jims.master.modules.finance.entity.InpBillDetail;
import com.jims.master.modules.sys.dao.CompanyDao;
import com.jims.master.modules.sys.utils.DeptUtils;
import com.jims.master.modules.sys.utils.DictUtils;
import com.jims.master.modules.sys.utils.UserUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 病人在院信息Service
 * @author 赵宁
 * @version 2017-03-27
 */
@Service
@Transactional(readOnly = true)
public class PatVisitService extends CrudService<PatVisitDao, PatVisit> {
	@Autowired
	private PatVisitIndexService patVisitIndexService;

	@Autowired
	private PatsInTransferringService patsInTransferringService;
	@Autowired
	private PatsInUnnursingService patsInUnnursingService;
	@Autowired
	private LiveRequisitionService liveRequisitionService;
    @Autowired
    private PatVisitDao patVisitDao;
    @Autowired
	private CompanyDao companyDao;
    @Autowired
	private InpBillDetailDao inpBillDetailDao;
    @Autowired
    private ClinicMasterDao clinicMasterDao;
    @Autowired
    private PatMasterIndexDao patMasterIndexDao;

	public PatVisit get(String id) {
		return super.get(id);
	}
	
	public List<PatVisit> findList(PatVisit patVisit) {
		return super.findList(patVisit);
	}

	public Page<PatVisit> findPageVist(Page<PatVisit> page, PatVisit patVisit) {
		return super.findPage(page, patVisit);
	}

	/**
	 * 护士端-在院病人列表数据查询
	 * @param patVisit
	 * @return
	 * @author CTQ
	 */
	public List<BaseDto> findPatientList( PatVisit patVisit) {
		return  dao.findPatientList(patVisit);
	}
	/**
	 * 护士端-出院病人列表数据查询
	 * @param patVisit
	 * @return
	 * @author CTQ
	 */
	public List<BaseDto> finOutPatientList( PatVisit patVisit) {
		return  dao.finOutPatientList(patVisit);
	}
	/**
	 * 查询病人列表
	 * @param page 分页对象
	 * @param patVisit
	 * @return
	 */
	public Page<PatVisit> findPage(Page<PatVisit> page, PatVisit patVisit) {
		patVisit.updateOrgId();
		patVisit.setPage(page);
		return  page.setList(dao.findPatVisit(patVisit));
	}

	/**
	 * 根据条件查询在院病人列表
	 * @param page
	 * @param patVisit
	 * @return
	 * @author 	CTQ
	 */
	public Page<PatVisit> findBedCardPage(Page<PatVisit> page, PatVisit patVisit) {
		patVisit.updateOrgId();
		List<PatVisit> patVisitList = dao.findBedCard(patVisit);
		page.setCount(patVisitList.size());
		page.setList(patVisitList);
		return  page;
	}


	/**
	 * 卡片打印
	 * @param patVisit
	 * @return
	 */
	public String bedsideCardPrint(PatVisit patVisit){
		Map map = new HashMap();
		patVisit.updateOrgId();
		patVisit.setWardCode(UserUtils.getUser().getOrgDept().getId());
        List<BaseDto> baseDtoList = dao.bedsideCardPrint(patVisit);
		String printPath = PrintPdfUtils.previewPdf(UserUtils.getUser().getId(), "his/nurse/bedsideCard.jasper", map, baseDtoList, "bedsideCardPrint");
		return printPath;
	}
	/**
	 * 住院患者片打印
	 * @param patVisit
	 * @return
	 */
	public String normalPrint(PatVisit patVisit){
		Map map = new HashMap();
		patVisit.updateOrgId();
		patVisit.setWardCode(UserUtils.getUser().getOrgDept().getId());
		List<PatVisit> patVisitList = dao.findBedCard(patVisit);
		BaseDto dto = new BaseDto();
		if (patVisitList!=null&&patVisitList.size()>0){
			dto.put("name",patVisitList.get(0).getPatVisitIndex()!=null?patVisitList.get(0).getPatVisitIndex().getName():"");
			dto.put("sex",DictUtils.getDictLabel(patVisitList.get(0).getPatVisitIndex()!=null?patVisitList.get(0).getPatVisitIndex().getSex():"","SEX_DICT",""));
			dto.put("visit_no",patVisitList.get(0).getVisitNo());
			dto.put("admission_date",DateUtils.formatDate(patVisitList.get(0).getAdmissionDate(),"yyyy-MM-dd"));
			dto.put("diagnosis",patVisitList.get(0).getDiagnosis());
		}
//		BaseDto dto = dao.findBedCardPrint(patVisit);
		map.putAll(dto);
		String printPath = PrintPdfUtils.previewPdf(UserUtils.getUser().getId(), "his/nurse/inHospPatientCard.jasper", map, null, "inHospPatientCard");
		return printPath;
	}
	/**
	 * 查询 病人基本信息 以及预交金记录
	 * @param visitNo
	 * @param orgId
	 * @return PatVisit
	 * @author 赵宁
	 */
	public PatVisit findPatInfoByNo(String visitNo,String orgId){
     return dao.findPatVisitByVisitNo(visitNo,orgId);
	}
	@Transactional(readOnly = false)
	public int save(PatVisit patVisit) {
		return super.save(patVisit);
	}
	
	@Transactional(readOnly = false)
	public int delete(PatVisit patVisit) {
		return super.delete(patVisit);
	}

	public String getMaxVisitNo(String visitNo){
		String acctNo=dao.getMaxVisitNo(visitNo,UserUtils.getOrgId());
		if(StringUtils.isNotBlank(acctNo)&& acctNo!=null){
			if (acctNo.contains("_")){
				acctNo=acctNo.substring(4,acctNo.indexOf("_"));
			}else {
				acctNo=acctNo.substring(4);
			}
			int no= Integer.parseInt(acctNo)+1;
            acctNo = String.valueOf(no);
            int acctL=acctNo.length();
            if(acctNo.length()<6){
                for (int i = 0; i < 6-acctL; i++) {
                    acctNo="0"+acctNo;
                }
            }
		}else{
			acctNo="00000"+1;
		}
		return acctNo;
	}

	/**
	 * 更改预交金余额
	 * @param id
	 * @param prepayments
	 * @author 陈涛
	 * @return
	 */
	public int updatePrepayments(String id,Double prepayments){
		return dao.updatePrepayments(id,prepayments) ;
	}

	/**
	 * 住院登记保存
	 * @param patVisit
	 * @param patVisitIndex
	 * @param patsInUnnursing
	 * @param patsInTransferring
	 * @param clinicId
	 * @author 陈涛
	 * @return
	 */
	@Transactional(readOnly = false)
	public  StringData saveInformation(PatVisit patVisit,PatVisitIndex patVisitIndex,PatsInUnnursing patsInUnnursing,PatsInTransferring patsInTransferring,String clinicId){
		int i = 0 ;
        ClinicMaster clinicMaster = clinicMasterDao.get(clinicId);
        String patientId ="";
        if(clinicMaster==null){
            String cardNo=patVisitIndex.getIdNo();
            PatMasterIndex patMasterIndex=null;
            if(StringUtils.isNotBlank(cardNo)){
                patMasterIndex=patMasterIndexDao.getIdNo(cardNo);
                if(patMasterIndex!=null){
                    patientId = patMasterIndex.getId();
                }else{
                    patMasterIndex=new PatMasterIndex();
					patMasterIndex.preInsert();
                    patientId = NumberUtils.getPatMasterId();
                    patMasterIndex.setId(patientId);
                    patMasterIndex.setInputCode(ChineseCharToEnUtils.getAllFirstLetter(patVisitIndex.getName()));
                    patMasterIndex.setName(patVisitIndex.getName());
                    patMasterIndex.setSex(patVisitIndex.getSex());
                    patMasterIndex.setAge(patVisitIndex.getAge());
                    patMasterIndex.setIdNo(patVisitIndex.getIdNo());
					patMasterIndex.updateOrgId();
                    patMasterIndexDao.insert(patMasterIndex);
                }
            }else{
				patMasterIndex=new PatMasterIndex();
				patMasterIndex.preInsert();
				patientId = NumberUtils.getPatMasterId();
				patMasterIndex.setId(patientId);
				patMasterIndex.setInputCode(ChineseCharToEnUtils.getAllFirstLetter(patVisitIndex.getName()));
				patMasterIndex.setName(patVisitIndex.getName());
				patMasterIndex.setSex(patVisitIndex.getSex());
				patMasterIndex.setAge(patVisitIndex.getAge());
				patMasterIndex.setIdNo(patVisitIndex.getIdNo());
				patMasterIndex.updateOrgId();
				patMasterIndexDao.insert(patMasterIndex);
            }
        }else{
            patientId =clinicMaster.getPatientId();
        }

        String orgId=UserUtils.getOrgId();
        SimpleDateFormat df = new SimpleDateFormat("yyyy");//设置日期格式
        String time = (df.format(new Date()));
        String visitNo = time + getMaxVisitNo(time);
        patVisit.setPatientId(patientId);
        patVisit.setInFlag("0");
        patVisit.setOrgId(orgId);
        patVisit.setDeptFlag("0");
        patVisit.setWardFlag("0");
        patVisit.setPrepayments("0");
        patVisit.setVisitNo(visitNo);
        patVisit.setClinicId(clinicId);
        patVisit.setVisitNumber(dao.getMaxVisitNumber(patientId,UserUtils.getOrgId()));
        PatVisit patVisitOld=patVisitDao.getPatient(patVisit);
        if(patVisitOld!=null){
            StringData data=new StringData();
            data.setCode("error");
            data.setData("病人已经在院，请勿重新入院");
            return data;
        }
		//添加pat_visit表
		super.save(patVisit);
		String visitId = patVisit.getId();
		//添加pat_visit_index表
		patVisitIndex.setVisitId(visitId);
		patVisitIndex.setInsuranceNo(null);
		patVisitIndex.setOrgId(orgId);
		patVisitIndexService.save(patVisitIndex);
		//添加pats_in_transferring表
		patsInTransferring.setPatientId(patientId);
		patsInTransferring.setVisitId(visitId);
		patsInTransferring.setDeptTransferTo(patVisit.getDeptAdmissionTo());
		patsInTransferring.setTransferDate(patVisit.getAdmissionDate());
		patsInTransferring.setOrgId(orgId);
		patsInTransferringService.save(patsInTransferring);
		//添加pats_in_unnursing表
		patsInUnnursing.setPatientId(patientId);
		patsInUnnursing.setVisitId(visitId);
		patsInUnnursing.setOrgId(orgId);
		patsInUnnursing.setWardTransferTo(patVisit.getWardAdmissionTo());
		patsInUnnursing.setTransferDate(patVisit.getAdmissionDate());
		patsInUnnursingService.save(patsInUnnursing);
		//修改住院通知单状态
		 i = liveRequisitionService.upDateInFlge(clinicId,"1");
        StringData data=new StringData();
        data.setCode("success");
        data.setData("保存病人在院信息成功");
        Map map = new HashMap();
        map.put("visitId",visitId);
        data.setDataMap(map);
		return data;
	}


    /**
     * 查询患者相关信息
     * @param patientId
     * @return
     */
    public PatVisit findCommonInfo(String patientId,String visitId) {
        return this.patVisitDao.findCommonInfo(patientId,visitId);
    }


	@Transactional(readOnly = false)
	public int updateUser(PatVisit patVisit){
		int num = 0;
		num = this.patVisitDao.updateUser(patVisit);
		return num;
	}

	/**
	 * 护士端--查询病人基本信息
 	 * @param patVisit
	 * @return PatVisit
	 * @author 赵宁
	 */
	public PatVisit getPatInfo(PatVisit patVisit){
		return patVisitDao.getPatInfo(patVisit);
	}

	/**
	 * 护理端-一日清单打印
	 * @param patVisit
	 * @return
	 * @author CTQ
	 */
	public String printBillItems(PatVisit patVisit){
		//PatVisit pv = patVisitDao.findPatVisitByVisitNo(patVisit.getVisitNo(),UserUtils.getOrgId());
		List<Object> objectList = Lists.newArrayList();
		Map map =new HashMap();
		patVisit.updateOrgId();
		List<PatVisit> patVisitList = patVisitDao.findAllList(patVisit);

			if (patVisitList!=null&&patVisitList.size()>0){
			for (PatVisit pv : patVisitList){
				map =new HashMap();
				//获取患者入院时间、出院时间
				String inDate ="";
				if (pv.getAdmissionDate()!=null){
					inDate = DateFormatUtils.format(pv.getAdmissionDate(),"yyyy-MM-dd"); //入院时间
				}
				String outDate = "";
				if (pv.getDischargeDate()!=null){
					outDate = DateFormatUtils.format(pv.getDischargeDate(),"yyyy-MM-dd HH:mm:ss");
				}
				map.put("hospital",UserUtils.getUser().getCompany().getOrgName());
				map.put("visit_no",pv.getVisitNo());
				map.put("name",pv.getPatVisitIndex().getName());
				map.put("sex",DictUtils.getDictLabel(pv.getPatVisitIndex().getSex(),"SEX_DICT",""));
				map.put("bed_no",pv.getBedNo());
				map.put("ward", DeptUtils.getDeptName(pv.getWardCode(),""));
				map.put("dept",DeptUtils.getDeptName(pv.getDeptStayed(),""));
				map.put("in_date",inDate);   //入院时间
				map.put("charge_type",DictUtils.getDictLabel(pv.getPatVisitIndex().getChargeType(),"CHARGE_TYPE_DICT",""));//身份

				map.put("start_time",patVisit.getStartDate()+" 00:00:00");
				map.put("end_time",patVisit.getEndDate()+" 23:59:59");
				map.put("print_date", DateUtils.getDateTime());//打印时间
				map.put("printOpera",UserUtils.getUser().getName());

				InpBillDetail ibd = new InpBillDetail();
				ibd.setPatientId(pv.getPatientId());
				ibd.setVisitId(pv.getId());
				ibd.updateOrgId();
				Double day_costs = inpBillDetailDao.findSumCharges(ibd);
				map.put("day_costs", day_costs);    //当日费用小计
				ibd.setStartTime(patVisit.getStartDate());
				ibd.setEndTime(patVisit.getEndDate());
				Double total_costs = inpBillDetailDao.findSumCharges(ibd);
				map.put("total_costs", total_costs);    //累计费用金额
				map.put("deposit", 0);    //押金
				map.put("balance", 0);    //余额
				List<BaseDto> lists = inpBillDetailDao.getBillItems(pv);
				map.put("list", lists);    //余额
				objectList.add(map);

			}
		}
		Map   dtoMap= new HashMap();
		if(objectList.size()<1){
			return "暂无数据";
		}else {
			dtoMap.put("SUBREPORT_DIR","his/nurse/dayOfListing_subReport.jasper");
		}

		String printPath= PrintPdfUtils.previewPdf(UserUtils.getUser().getId(),"his/nurse/dayOfListing.jasper",dtoMap,objectList,"dayOfListing");
		return  printPath;
	}

	/**
	 * 查询病人基本信息以及费用信息
	 * @param inpBillDetail
	 * @return PatVisit
	 * @author 赵宁
	 */
	public PatVisit getPatInfoBill(InpBillDetail inpBillDetail){
		return  dao.getPatBillInfo(inpBillDetail);
	}


    /**
     * 获取待退药医嘱患者列表
     * @param patVisit
     * @return
     */
    public Page<PatVisit> findByDrugInPage(Page<PatVisit> page, PatVisit patVisit ) {
        patVisit.setPage(page);
        page.setList(dao.findByDrugIn(patVisit));
        return page;
    }

	/**
	 * 获取病人最大就诊次数
	 * @param patientId
	 * @return
	 * @author CTQ
	 */
	private  int getMaxVisitNumber(String patientId){
		int num = dao.getMaxVisitNumber(patientId,UserUtils.getOrgId());
		return num;

	}

}